<template>
	<n-form ref="groupFromRef" label-placement="left" inline :label-width="80" :model="formData" :rules="groupRule">
		<n-form-item label="组名" path="name">
			<n-input v-model:value="formData.name" placeholder="输入姓名" />
		</n-form-item>
		<n-form-item label="组备注" path="remark">
			<n-input v-model:value="formData.remark"  style="width: 450px;" placeholder="备注" />
		</n-form-item>
	</n-form>
	<n-space justify="center">
		<div class="h-660px overflow-auto w-200px">
			<var-description-tree/>
		</div>
		<n-card style="max-width: 1024px;">
			<n-tabs class="mytab" v-model:value="activeItem" type="card" animated closable tab-style="min-width: 80px;"
				:on-close="handleTabClose">
				<n-tab-pane v-for="item, index in formData.items" :key="item.name" :name="index">
					<template #tab>
						{{ item.name }}
					</template>

				</n-tab-pane>
				<template #suffix>
					<n-button circle size="small" @click="handelAddTab">
						<template #icon>
							<svg-icon icon="material-symbols:add"></svg-icon>
						</template>
					</n-button>
				</template>
			</n-tabs>
			<n-form label-placement="left" :label-width="90">
				<n-space justify="space-between">
					<n-form-item style="width: 400px;">
						<template #label>
								<n-tooltip placement="bottom" trigger="hover">
									<template #trigger>
										<span class="flex justify-end cursor-pointer">
											文件名<svg-icon icon="ph:info-light"></svg-icon>
										</span>
									</template>
									<span> 可以使用左侧变量表中的变量进行编写 </span>
								</n-tooltip>
						</template>
						<n-input v-model:value="formData.items[activeItem].name" placeholder="输入文件名" />
					</n-form-item>
					<n-form-item style="width: 500px;">
						<template #label>
								<n-tooltip placement="bottom" trigger="hover">
									<template #trigger>
										<span class="flex justify-end cursor-pointer">
											文件路径<svg-icon icon="ph:info-light"></svg-icon>
										</span>
									</template>
									<span> 可以使用左侧变量表中的变量进行编写 </span>
								</n-tooltip>
						</template>
						<n-input v-model:value="formData.items[activeItem].path" placeholder="输入文件路径" />
					</n-form-item>
				</n-space>
				<n-space justify="space-between">
					<n-form-item label="备注">
						<n-input v-model:value="formData.items[activeItem].remark" placeholder="输入备注" type="textarea"
							style="width: 300px;" />
					</n-form-item>
					<n-form-item label="语言">
						<n-select style="width: 200px;" v-model:value="formData.items[activeItem].language" :options="languageOptions"
							value-field="label" @update:value="handleLanguageChange" />
					</n-form-item>
				</n-space>
			</n-form>
			<codemirror v-model:modelValue="formData.items[activeItem].code" placeholder="请输入代码..." :style="{ height: '400px' }"
				:autofocus="true" :indent-with-tab="true" :tab-size="2" :extensions="extensions" />


				<extra-var ref="extraValRef" :extra="formData.extra" />
			</n-card>
	</n-space>
	<n-space justify="center">

		<n-button text tag="a" href="http://freemarker.foofun.cn/pgui_quickstart_createconfiguration.html" target="_blank" type="primary">
			<template  #icon>
				<svg-icon icon="material-symbols:info-outline" />
			</template>
			模版语言 文档说明 （Freemarker 中文文档）
		</n-button>
	</n-space>
	<n-space justify="center" class="mt-4">
		<n-button type="primary" @click="handleSubmitForm">确定</n-button>
		<n-button @click="hendleCloseModal">取消</n-button>
	</n-space>
</template>

<script  setup lang='ts' >
import { FormInst, SelectOption } from 'naive-ui';
import {  onMounted, ref, toRefs, unref } from 'vue';

import { GenGroup, buildItem } from './index';
import { featchAddTemplateGroup, featchUpdateTemplateGroup } from "@/service/api/templateManage/index"

import { Codemirror } from 'vue-codemirror'
import { languageOptions } from './languageOptions';
import { oneDark } from '@codemirror/theme-one-dark'
import  varDescriptionTree  from "./varDescriptionTree.vue";
import  extraVar  from "./extraVar.vue";

type Props = {
	formData: GenGroup
	itemIndex?:number
}
const props = defineProps<Props>()
const { formData } = toRefs(props)
onMounted(async () => {
	formData.value.items = formData.value.items ? formData.value.items : [buildItem()]
})

const handleTabClose = (value: number) => {
	formData.value.items.splice(value, 1)

}
const handleLanguageChange = (value: string, option: SelectOption) => {
	const extensionsTemp = [oneDark]
	//@ts-ignore
	extensionsTemp.push(option.value())
	extensions.value = extensionsTemp
}
const handelAddTab = () => {
	if (vaildItemFrom()) {
		formData.value.items!.push(buildItem())
	}
}
const vaildItemFrom = (): boolean => {
	const temValue = formData.value.items
	for (var i: number = 0, len: number = temValue.length; i < len; i++) {
		const temp = temValue[i]
		if (!(temp.name && temp.path)) {
			window.$message?.error(`请检查第[${i + 1}]个文件的输入项是否合规！`)
			return false
		}
	}
	return true;
}

const hendleCloseModal = () => {
	emit("close")
}

function handleFetchResult(res: Service.RequestResult<unknown>) {
	if (!res.error) {
		hendleCloseModal()
		emit("list")
	}
}

function handleSubmitForm() {
	groupFromRef.value?.validate(e => {

		if (!e && vaildItemFrom()) {
			const extra:Record<string,string> = extraValRef?.value.refreshExtra()
			const value = unref(formData.value)
			value.extra = extra
			if (value.id) {
				featchUpdateTemplateGroup(value).then(handleFetchResult)
			} else {
				featchAddTemplateGroup(value).then(handleFetchResult)
			}
		}
	})
}

const emit = defineEmits(["list", "close"])
//@ts-ignore
const extensions = ref([languageOptions[0].value(), oneDark])

const groupRule = {
	name: { required: true, message: "请输入模版组名", trigger: 'input' },
}
const groupFromRef = ref<FormInst | null>(null)
const extraValRef = ref< any | null>(null)
console.info(props.itemIndex)
const activeItem = ref<number>( props.itemIndex ? props.itemIndex : 0)


// const inputKeyRef = (el:any)=>{
// 	if(el)inputKeyRefList.value.push(el)
// }

</script>

<style>
.mytab.n-tabs .n-tabs-pane-wrapper{
	position: inherit !important;
}
</style>
